package org.jeecg.common.modules.redis.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.jeecg.common.constant.CacheConstant;
import org.jeecg.common.constant.GlobalConstants;
import org.jeecg.common.modules.redis.receiver.RedisReceiver;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.IOException;
import java.time.Duration;

/**
 * 缓存配置-使用Lettuce客户端，自动注入配置的方式
 * 新版「RedisConfig」
 */
@Configuration
@EnableCaching //启用缓存
public class CacheConfig extends CachingConfigurerSupport {

    /**
     * 自定义缓存key的生成策略。默认的生成策略是看不懂的(乱码内容) 通过 Spring 的依赖注入特性进行自定义的配置注入并且此类是一个配置类可以更多程度的自定义配置
     */
    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(target.getClass().getName());
            stringBuilder.append(method.getName());
            for (Object param : params) {
                stringBuilder.append(param);
            }
            return stringBuilder.toString();
        };
    }

    /**
     * redis地址
     */
    @Value("${spring.redis.host}")
    private String host;

    /**
     * redis端口号
     */
    @Value("${spring.redis.port}")
    private int port;

    /**
     * redis密码
     */
    @Value("${spring.redis.password}")
    private String password;
    /**
     * redis用户名
     */
    @Value("${spring.redis.username}")
    private String username;
    /**
     * RedissonClient,单机模式
     * @return
     */
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redisson() throws IOException {
        Config config = new Config();
        System.out.println("redis://" + host + ":" + port);
//        config.useSingleServer().setAddress("redis://" + host + ":" + port).setPassword(password).setDatabase(15);
        config.useSingleServer().setAddress("redis://" + host + ":" + port).setDatabase(15);
        //设置全局默认看门狗机续期时间,如果在使用时不设置，则使用全局的，如果全局不设置，则使用默认的30000,单位毫秒
        // 如果业务超长，运行期间自动给锁续上新的有效时间，不用担心业务时间长，锁自动过期被删掉
        config.setLockWatchdogTimeout(10000);
        return Redisson.create(config);
    }
    /**
     * 缓存配置管理器
     */
    @Bean
    public CacheManager cacheManager(LettuceConnectionFactory factory) {
        // 设置 CacheManager 的 Key 序列化方式为 StringRedisSerializer, Value 序列化方式为 Jackson2JsonRedisSerializer
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig();
        RedisSerializationContext.SerializationPair<String> serializeKeysWith = RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer());
        RedisSerializationContext.SerializationPair<Object> serializeValuesWith = RedisSerializationContext.SerializationPair.fromSerializer(jacksonSerializer());
        RedisCacheConfiguration redisCacheConfiguration = defaultCacheConfig.serializeKeysWith(serializeKeysWith)
                .serializeValuesWith(serializeValuesWith);


        // 以锁写入的方式创建RedisCacheWriter对象
        RedisCacheWriter writer = RedisCacheWriter.lockingRedisCacheWriter(factory);

        // 创建默认缓存配置对象
        return RedisCacheManager.builder(writer).cacheDefaults(redisCacheConfiguration)

                /*
                 * withInitialCacheConfigurations：自定义缓存，可独立于默认配置
                 * disableCachingNullValues：禁用缓存空值。注意，任何涉及空值的Cache.put（对象，对象）操作都将出错。不会写给Redis，不会删除任何东西。之后，已经存在的密钥仍将在那里，其值与以前完全相同。
                 */
                // 自定义缓存 表字典信息 10分站
                .withCacheConfiguration(CacheConstant.SYS_DICT_TABLE_CACHE,
                        RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(10)).disableCachingNullValues())

                // 自定义缓存 首页统计 8h
                .withCacheConfiguration(CacheConstant.ORDER_COUNT_PAGE,
                        RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(8)).disableCachingNullValues())


                // 启用-> 将 RedisCaches 缓存 put/evict 操作与正在进行的 Spring 管理事务同步。
                .transactionAware()
                .build();
    }

    /**
     * 获取缓存操作助手对象
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory) {

        //创建Redis缓存操作助手RedisTemplate对象
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer<Object> jacksonSerializer = jacksonSerializer();
        RedisTemplate<String,Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // key序列化
        template.setKeySerializer(stringRedisSerializer);
        // value序列化
        template.setValueSerializer(jacksonSerializer);
        // hash的kv序列化
        template.setHashKeySerializer(stringRedisSerializer);
        template.setHashValueSerializer(jacksonSerializer);
        template.afterPropertiesSet();
        return template; // StringRedisTemplate是RedisTempLate<String, String>的子类
    }

    /**
     * redis 监听配置
     *
     * @param redisConnectionFactory redis 配置
     */
    @Bean
    public RedisMessageListenerContainer redisContainer(RedisConnectionFactory redisConnectionFactory, RedisReceiver redisReceiver, MessageListenerAdapter commonListenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(redisConnectionFactory);
        container.addMessageListener(commonListenerAdapter, new ChannelTopic(GlobalConstants.REDIS_TOPIC_NAME));
        return container;
    }

    @Bean
    MessageListenerAdapter commonListenerAdapter(RedisReceiver redisReceiver) {
        MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(redisReceiver, "onMessage");
        messageListenerAdapter.setSerializer(jacksonSerializer());
        return messageListenerAdapter;
    }

    /**
     * 将RedisTemplate的Value序列化方式由JdkSerializationRedisSerializer更换为Jackson2JsonRedisSerializer
     * 此种序列化方式结果清晰、容易阅读、存储字节少、速度快，所以推荐更换
     */
    private static Jackson2JsonRedisSerializer<Object> jacksonSerializer() {
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
                ObjectMapper.DefaultTyping.NON_FINAL/*, JsonTypeInfo.As.PROPERTY*/);

        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        return jackson2JsonRedisSerializer;
    }

}
